package be.kuleuven.peno3.mobiletoledo.server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.json.simple.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Path ("/MessageHandler")
public class MessageServer {

	protected DatabaseManager manager = DatabaseManager.getInstance();

	@GET
	@Path ("/getMessages")
	@Produces ("application/json")
	public String getMessages(@QueryParam("course_id") int course_id){
		String query = "SELECT * FROM Messages";
	    if (course_id!=0) query += " WHERE course_id='"+course_id+"'";
	    query += " order by id desc";
	    if(course_id==0) query+=" limit 20";
	    
		String result = queryForMessages(query);
		manager.disconnect();
		return result;
	}
	
	@GET
	@Path ("/getMessage")
	@Produces ("application/json")
	public String getMessage(@QueryParam("message_id") int messageId){
		String query = "SELECT * FROM Messages WHERE id='"+messageId+"'";
	    
		String result = queryForMessages(query);
		manager.disconnect();
		return result;
	}
	
	@SuppressWarnings({ "unchecked" })
	@GET
	@Path ("/addMessage")
	@Produces ("application/json")
	public String addMessage(@QueryParam("author") String author, @QueryParam("body") String body, @QueryParam("course_id") int course_id, @QueryParam("title") String title, @QueryParam("cal") String cal){
		JSONObject result = new JSONObject();
		try {
			String query = "INSERT INTO Messages(author, content, course_id, title, date) VALUES ('"+author+"','"+body+"','"+course_id+"','"+title+"', '"+cal+"')";
			manager.update(query);
			
			manager.disconnect();
		} catch (SQLException e1) {
			result.put("result", "INSERT of credentials failed");
			e1.printStackTrace();
			return result.toString();
		}
		
		result.put("result", "Message successfully added");
		manager.disconnect();
		return result.toString();
	}
	
	@SuppressWarnings("static-access")
	private String queryForMessages(String query) {
		JsonArray messages = new JsonArray();
		ResultSet rs = manager.query(query);
		Gson gson = new Gson();
		try {
			while(rs.next()) {
				JsonObject message = (JsonObject) gson.toJsonTree(manager.getColumnValues(rs));
				
				//get corresponding course from the database
				int course_id = message.get("course_id").getAsInt();
				if(course_id != 0) {
					query = "SELECT * FROM Courses WHERE id='" + course_id + "' limit 1";
					message.add("course", querySimpleTable(query).get(0));
				}

				messages.add(message);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		String asString = messages.toString();
		return asString;
	}
	
	
	@SuppressWarnings({"static-access", "unchecked", "rawtypes" })
	private JsonArray querySimpleTable(String query) {
		Vector course = new Vector();
		ResultSet rs = manager.query(query);
		Gson gson = new Gson();
		try {
			while(rs.next()) {
				course.add(manager.getColumnValues(rs));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return (JsonArray) gson.toJsonTree(course);
	}

	
}
